package com.wp.service.Impl;

import com.wp.dao.BookShopDao;
import com.wp.service.BookShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author: WangPeng
 * @createTime: 2022/11/14 17:39
 * @description:
 * @version: v1.0
 */
@Service
public class BookShopServiceImpl implements BookShopService {

    @Autowired
    private BookShopDao bookShopDao;
    @Override
    //事务注解
    //propagation: 定义事务的传播属性。默认为REQUEIRED.
    //isolation:设置事务隔离属性，DEFAULT属性默认是READ_COMMITTED。
    //rollbackFor:指定哪些异常回滚。
    //noRollbackFor:指定哪些异常类型不会滚。
    //timeout: 默认永不超时,如果代码执行时间超过指定时间（单位为秒） 则事务也会回滚。
    // readOnly：默认是false，true 表示只读数据库，没有事务操作
    @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.DEFAULT,
                   rollbackFor = {SQLException.class, IOException.class},
                   noRollbackFor ={ClassNotFoundException.class,NumberFormatException.class},
                   timeout = 2,
                   readOnly = false)
    public void buyBook(String isbn, String username) {
        //1、根据图书编号查询图书的价格
        int price = bookShopDao.findBookPriceByIsbn(isbn);

        //2、查询库存，并判断库存是否充足
        int stock = bookShopDao.findStockByIsbn(isbn);
        if (stock >0){
            //3、修改库存
            bookShopDao.updateBookStock(isbn);
        }else {
            throw new RuntimeException("编号为："+isbn+"的图书;库存不足。");
        }

//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        //4、查询账户余额，并判余额是否充足
        int balance = bookShopDao.findBalanceByUsername(username);
        if (balance >= price){
            //5、修改账户余额
            bookShopDao.updateAccount(username,price);
        }else {
            throw new RuntimeException(username+"账户余额不足。");
        }

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void buyManyBook(List<String> isbns, String username) {
        for (String isbn : isbns) {
            buyBook(isbn,username);
        }
    }
}
